package com.lwj.liwanjia.utils;

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.amap.api.maps.model.Text;
import com.bumptech.glide.Glide;
import com.google.android.flexbox.AlignItems;
import com.google.android.flexbox.FlexDirection;
import com.google.android.flexbox.FlexWrap;
import com.google.android.flexbox.FlexboxLayout;
import com.google.android.flexbox.FlexboxLayoutManager;
import com.google.android.flexbox.JustifyContent;
import com.google.gson.Gson;
import com.lwj.liwanjia.R;
import com.lwj.liwanjia.adapter.SelectAdapter;
import com.lwj.liwanjia.adapter.SelectAdapter1;
import com.lwj.liwanjia.adapter.TypeAdapter;
import com.lwj.liwanjia.bean.AddGwcBean;
import com.lwj.liwanjia.bean.JieSuanBean;
import com.lwj.liwanjia.bean.ScAddGwcBean;
import com.lwj.liwanjia.bean.ScSelectBean;
import com.lwj.liwanjia.bean.SpPriceBean;
import com.lwj.liwanjia.impl.AddGwcView;
import com.lwj.liwanjia.impl.ScAddGwcView;
import com.lwj.liwanjia.impl.SpPriceView;
import com.lwj.liwanjia.impl.ToBuyView;
import com.lwj.liwanjia.presenter.AddScGwcPresenter;
import com.lwj.liwanjia.presenter.ScAddGwcPresenter;
import com.lwj.liwanjia.presenter.SpPricePresenter;
import com.lwj.liwanjia.presenter.ToBuyPresenter;
import com.lwj.liwanjia.view.activity.indent.IndentActivity;
import com.lwj.liwanjia.view.activity.login.LoginActivity;
import com.superrecycleview.superlibrary.recycleview.SuperRecyclerView;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import rx.Subscription;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;
import rx.schedulers.Schedulers;

/**
 * Created by Administrator on 2017/10/12.
 */

public class SpBuyDialog extends Dialog implements View.OnClickListener, ScAddGwcView, AddGwcView, ToBuyView, SpPriceView {

    private Context context;
    private List<ScAddGwcBean.DataBean.LableBean> list = new ArrayList<>();
    private SuperRecyclerView rlvSelect;
    private SelectAdapter1 adapter;
    private TextView sure;
    private TextView number;
    private ImageView ivCancle;
    private TextView tvKuCun;
    private TextView tvSpPrice;
    private ImageView ivShangpin;
    private TextView tvDecrease;
    private TextView tvAdd;
    private ScAddGwcPresenter presenter;//获取基本数据
    private String token;
    private TextView tvInfor;
    private String infor;
    private AddScGwcPresenter addScGwcPresenter;//加入购物车
    private SpPricePresenter spPricePresenter;//规格不同价格等不同
    private Map<String, Object> map;//token,数量
    private TextView gouwucheNumber;//购物车中商品数量
    private ToBuyPresenter toBuyPresenter;
    private String type;
    private List<ScSelectBean.SelectBean> dataList;
    private int canBuy = 0;//商城判断是否能够购买（0-不能，1-能）
    private RxBus rxBus;
    private Map<String, Object> maps;
    private Subscription subscription;
    private String nowCode;//购买或加入购物车时不同规格的最终商品编码

    public SpBuyDialog(@NonNull Context context, String commodityCode, TextView gouwucheNumber, String type, double price) {
        super(context, R.style.MyDialog);
        this.context = context;
        this.gouwucheNumber = gouwucheNumber;
        this.type = type;
        map = new HashMap<>();
        presenter = new ScAddGwcPresenter(this);
        addScGwcPresenter = new AddScGwcPresenter(this);
        spPricePresenter = new SpPricePresenter(this);
        toBuyPresenter = new ToBuyPresenter(this);
        token = SpfUtils.getSpfUtils(context).getToken();
        presenter.getScData(token, commodityCode, price);
        nowCode = commodityCode;
        map.put("commodityCode", commodityCode);//选不同组合时始终上传详情页传过来的商品编码
        map.put("token", token);
        map.put("nowPrice", price);
        dataList = new ArrayList<>();
        rxBus = RxBus.getInstance();
        maps = new HashMap<>();
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.shangcheng_select_item);
        initView();
    }

    private void initView() {
        Window window = getWindow();
        window.setGravity(Gravity.BOTTOM);
        window.setWindowAnimations(R.style.dialog_animation);
        setCanceledOnTouchOutside(false);
        WindowManager.LayoutParams params = window.getAttributes();
        params.width = params.MATCH_PARENT;
        params.height = params.WRAP_CONTENT;
        window.setAttributes(params);
        rlvSelect = (SuperRecyclerView) findViewById(R.id.rlv_select);
        LinearLayoutManager manager = new LinearLayoutManager(context);
        manager.setOrientation(LinearLayoutManager.VERTICAL);
        rlvSelect.setLayoutManager(manager);
        rlvSelect.setRefreshEnabled(false);
        rlvSelect.setLoadMoreEnabled(false);
        adapter = new SelectAdapter1(context, list);
        rlvSelect.setAdapter(adapter);
        sure = (TextView) findViewById(R.id.tv_sure);
        ivCancle = (ImageView) findViewById(R.id.iv_delete);
        number = (TextView) findViewById(R.id.tv_number);
        tvKuCun = (TextView) findViewById(R.id.tv_sp_kucun);
        tvSpPrice = (TextView) findViewById(R.id.tv_sp_price);
        ivShangpin = (ImageView) findViewById(R.id.iv_image);
        tvDecrease = (TextView) findViewById(R.id.tv_decrease);
        tvAdd = (TextView) findViewById(R.id.tv_add);
        tvInfor = (TextView) findViewById(R.id.tv_infor);
        sure.setOnClickListener(this);
        tvAdd.setOnClickListener(this);
        tvDecrease.setOnClickListener(this);
        ivCancle.setOnClickListener(this);
        subscription = rxBus.toObserverable(Map.class).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe(new Action1<Map>() {
            @Override
            public void call(Map maps) {
                setData(maps);
                ScSelectBean scSelectBean = new ScSelectBean();
                scSelectBean.setDataList(dataList);
                spPricePresenter.getNowPrice(map, scSelectBean);
            }
        });
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.tv_sure:
                maps = adapter.getMaps();
                if (maps.size() != list.size()) {
                    Toast.makeText(context, "请选择" + infor, Toast.LENGTH_SHORT).show();
                    return;
                }
                setData(maps);
                ScSelectBean scSelectBean = new ScSelectBean();
                String activePrice = tvSpPrice.getText().toString().replace("￥", "");
                String price = activePrice.split("元")[0];
                map.put("nowPrice", Double.parseDouble(price));
                map.put("num", number.getText().toString());
                map.put("commodityCode", nowCode);
                scSelectBean.setDataList(dataList);
                if (canBuy == 0) {
                    Toast.makeText(context, "没有该商品不能购买", Toast.LENGTH_SHORT).show();
                    return;
                }
                String kucun = tvKuCun.getText().toString().replace("库存", "");
                String buyNum = number.getText().toString();
                if (Integer.parseInt(kucun) < Integer.parseInt(buyNum)) {
                    Toast.makeText(context, "库存不足", Toast.LENGTH_SHORT).show();
                    return;
                }
                if (type.equals("加入购物车")) {
                    addScGwcPresenter.scAddGwc(map, scSelectBean);
                } else if (type.equals("立即购买")) {
                    toBuyPresenter.toBuyData(map, scSelectBean);
                }
                break;
            case R.id.iv_delete:
                dismiss();
                break;
            case R.id.tv_decrease:
                String sum = number.getText().toString();
                int num = Integer.parseInt(sum);
                if (num == 1) {
                    return;
                }
                number.setText((--num) + "");
                break;
            case R.id.tv_add:
                String sum1 = number.getText().toString();
                int num1 = Integer.parseInt(sum1);
                number.setText((++num1) + "");
                break;
        }
    }

    public void setData(Map<String, Object> maps) {
        for (Object obj : maps.keySet()) {
            ScSelectBean.SelectBean selectBean = new ScSelectBean.SelectBean();
            String key = (String) obj;
            selectBean.setTitle(key);
            selectBean.setType((String) maps.get(key));
            dataList.add(selectBean);
        }
    }

    @Override
    public void showError(Exception e) {
        Toast.makeText(context, "数据加载失败", Toast.LENGTH_SHORT).show();
    }

    @Override
    public void getNowPrice(SpPriceBean spPriceBean) {
        if (spPriceBean.getState() == 1) {
            dataList.clear();
            if (spPriceBean.getData().getHave() == 1) {
                double nowPrice = spPriceBean.getData().getNowPrice();
                String imageUrl = spPriceBean.getData().getImageUrl();
                tvSpPrice.setText("￥" + nowPrice);
                if (imageUrl != null && !TextUtils.isEmpty(imageUrl)) {
                    Glide.with(context).load(imageUrl).error(R.mipmap.zhanweitu_07).transform(new GlideRoundTransform(context)).into(ivShangpin);
                }
                tvKuCun.setText("库存" + spPriceBean.getData().getStock());
                nowCode = spPriceBean.getData().getCommodityCode();
                canBuy = 1;
                sure.setBackgroundColor(context.getResources().getColor(R.color.colorEC921A));
            } else if (spPriceBean.getData().getHave() == 0) {
                canBuy = 0;
                Toast.makeText(context, "没有该商品", Toast.LENGTH_SHORT).show();
                sure.setBackgroundColor(context.getResources().getColor(R.color.colorCECECE));
            }
        }
    }

    @Override
    public void toBuyData(JieSuanBean jieSuanBean) {
        if (jieSuanBean.getState() == 0) {
            Toast.makeText(context, "结算失败", Toast.LENGTH_SHORT).show();
        } else {
            dataList.clear();
            Intent intent = new Intent(context, IndentActivity.class);
            intent.putExtra("data", jieSuanBean.getData());
            context.startActivity(intent);
            dismiss();
        }
    }

    @Override
    public void addGouWuChe(AddGwcBean addGwcBean) {
        if (addGwcBean.getState() == 0) {
            Toast.makeText(context, "加入购物车失败", Toast.LENGTH_SHORT).show();
        } else {
            if (addGwcBean.isData()) {
                dataList.clear();
                Toast.makeText(context, "加入购物车成功", Toast.LENGTH_SHORT).show();
                gouwucheNumber.setText((Integer.parseInt(gouwucheNumber.getText().toString()) + 1) + "");
                dismiss();
            } else {
                Toast.makeText(context, "加入购物车失败", Toast.LENGTH_SHORT).show();
            }
        }
    }

    @Override
    public void getScData(ScAddGwcBean scAddGwcBean) {
        if (scAddGwcBean.getState() == 0) {
            context.startActivity(new Intent(context, LoginActivity.class));
            dismiss();
        } else if (scAddGwcBean.getState() == 1) {
            tvKuCun.setText("库存" + scAddGwcBean.getData().getStock());
            tvSpPrice.setText("￥" + scAddGwcBean.getData().getNowPrice());
            String image_url = scAddGwcBean.getData().getImage_url();
            if (!TextUtils.isEmpty(image_url)) {
                Glide.with(context).load(image_url).error(R.mipmap.zhanweitu_07).transform(new GlideRoundTransform(context)).into(ivShangpin);
            }
            list.clear();
            List<ScAddGwcBean.DataBean.LableBean> lable = scAddGwcBean.getData().getLable();
            StringBuffer sp = new StringBuffer();
            if (lable != null && lable.size() > 0) {
                rlvSelect.setVisibility(View.VISIBLE);
                if(lable.size()>=2){
                    rlvSelect.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,350));
                }
                list.addAll(lable);
                for (int i = 0; i < lable.size(); i++) {
                    sp.append(lable.get(i).getTitle() + "/");
                }
                infor = sp.substring(0, sp.lastIndexOf("/"));
                tvInfor.setText("请选择 " + infor);
            } else {
                rlvSelect.setVisibility(View.GONE);
                canBuy = 1;
                sure.setBackgroundColor(context.getResources().getColor(R.color.colorEC921A));
                tvInfor.setVisibility(View.GONE);
            }
            adapter.setSize(list.size());
            adapter.notifyDataSetChanged();
        }
    }

    @Override
    protected void onStop() {
        if (!subscription.isUnsubscribed()) {
            subscription.unsubscribe();
        }
        super.onStop();
    }
}
